import React, { useState, ReactText, useEffect } from 'react';
import { Button, Tag, Space, Avatar, message, Modal } from 'antd';
import ProList from '@ant-design/pro-list';
import { request, Access, useAccess } from 'umi';
import { api } from '@/global';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProFormSelect,
  ProFormDigit,
  ProFormSwitch,
  ProFormDependency,
} from '@ant-design/pro-form';
type pramaryType = {
  id: number;
  title: number;
  deptName: string;
};

type UpdateResponseType = {
  id: number;
  storageName: string;
  storageLongitude: string;
  storageLatitude: string;
  storageAddress: string;
  deptId: number;
};

type deptTyp = {
  id: string;
  deptName: string;
};

const InsertComponent = (props: any) => {
  return (
    <ModalForm<any>
      title="新增存储室"
      trigger={<a>新增</a>}
      autoFocusFirstInput
      onFinish={async (values) => {
        const data = await request(api.insertOrUpdateStoreInfo, {
          method: 'POST',
          data: {
            ...values,
          },
        });

        if (data.success) {
          message.success('添加成功');
          props?.initData();
        } else {
          message.error('添加失败');
        }

        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="storageName"
          label="存储室名称"
          placeholder="请输入存储室名称"
          rules={[
            {
              required: true,
              message: '请输入存储室名称',
            },
          ]}
        />

        <ProFormSelect
          width="sm"
          name="deptId"
          label="所属系部"
          request={async () => {
            const deptData = await request(api.getAllDept, {});
            const list: any[] = [];

            deptData.data.map((item: deptTyp) => {
              list.push({
                label: item.deptName,
                value: item.id,
              });
            });

            return list;
          }}
          rules={[
            {
              required: true,
              message: '请选择所属系部',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea
          name="storageAddress"
          width="lg"
          label="详细地址"
          placeholder="请输入详细的地址"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          label="所在经度"
          name="storageLongitude"
          width="sm"
          rules={[
            {
              required: true,
              message: '请输入所在经度',
            },
            {
              pattern:
                /^[\-\+]?(0(\.\d{1,8})?|([1-9](\d)?)(\.\d{1,8})?|1[0-7]\d{1}(\.\d{1,8})?|180(([.][0]{1,8})?))$/,
              message: '请输入正确的经度',
            },
          ]}
        />
        <ProFormText
          label="所在纬度"
          name="storageLatitude"
          width="sm"
          tooltip="小数点后三位"
          rules={[
            {
              required: true,
              message: '请输入所在纬度',
            },
            {
              pattern: /^[\-\+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,20})?)$/,
              message: '请输入正确的纬度',
            },
          ]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};

const UpdateComponent = (props: any) => {
  const [visible, SetVisible] = useState<boolean>(false);
  const [initValue, SetInitValue] = useState<UpdateResponseType>();

  const initData = async () => {
    const r = await request(api.getStoreInfoById, {
      params: {
        id: props.selectedRowKeys[0],
      },
    });

    SetInitValue(r.data);
  };

  useEffect(() => {
    if (props.selectedRowKeys.length == 1) {
      initData();
    }
  }, [props.selectedRowKeys]);

  return (
    <ModalForm<any>
      title="新增存储室"
      trigger={
        <a
          onClick={() => {
            if (props.selectedRowKeys) {
              if (props.selectedRowKeys.length !== 1) {
                message.error('请选择唯一一项进行修改');
              } else {
                SetVisible(true);
              }
            }
          }}
        >
          修改
        </a>
      }
      modalProps={{
        onCancel: () => SetVisible(false),
      }}
      visible={visible}
      autoFocusFirstInput
      onFinish={async (values) => {
        const data = await request(api.insertOrUpdateStoreInfo, {
          method: 'POST',
          data: {
            ...values,
            id: props.selectedRowKeys[i],
          },
        });

        if (data.success) {
          message.success('添加成功');
          props?.initData();
          SetVisible(false);
        } else {
          message.error('添加失败');
        }

        return true;
        SetVisible(false);
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="storageName"
          label="存储室名称"
          placeholder="请输入存储室名称"
          fieldProps={{
            value: initValue?.storageName,
          }}
          rules={[
            {
              required: true,
              message: '请输入存储室名称',
            },
          ]}
        />

        <ProFormSelect
          width="sm"
          name="deptId"
          label="所属系部"
          initialValue={initValue?.deptId}
          fieldProps={{
            value: initValue?.deptId,
          }}
          request={async () => {
            const deptData = await request(api.getAllDept, {});
            const list: any[] = [];

            deptData.data.map((item: deptTyp) => {
              list.push({
                label: item.deptName,
                value: item.id,
              });
            });

            return list;
          }}
          rules={[
            {
              required: true,
              message: '请选择所属系部',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea
          name="storageAddress"
          width="lg"
          label="详细地址"
          fieldProps={{
            value: initValue?.storageAddress,
          }}
          initialValue={initValue?.storageAddress}
          placeholder="请输入详细的地址"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          label="所在经度"
          name="storageLongitude"
          tooltip="小数点后10位"
          fieldProps={{
            value: initValue?.storageLongitude,
          }}
          initialValue={initValue?.storageLongitude}
          width="sm"
          rules={[
            {
              required: true,
              message: '请输入所在经度',
            },
            {
              pattern:
                /[\+\-]?((?:[0-9]|[1-9][0-9]|1[0-7][0-9])\.([0-9]{0,10})|[0-9]|[1-9][0-9]|1[0-7][0-9]|180)/,
              message: '请输入正确的经度',
            },
          ]}
        />
        <ProFormText
          label="所在纬度"
          name="storageLatitude"
          width="sm"
          tooltip="小数点后10位"
          fieldProps={{
            value: initValue?.storageLatitude,
          }}
          initialValue={initValue?.storageLatitude}
          rules={[
            {
              required: true,
              message: '请输入所在纬度',
            },
            {
              pattern: /[\+\-]?((?:[0-9]|[1-8][0-9])\.([0-9]{0,10}|[0-9]|[1-8][0-9]|90))/,
              message: '请输入正确的纬度',
            },
          ]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};

export default (props: any) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<ReactText[]>([]);
  const [dataSource, SetDataSource] = useState<pramaryType[]>();
  const access = useAccess();
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: ReactText[]) => {
      setSelectedRowKeys(keys);
      props.getSelectRowKeys(keys);
    },
  };

  const initData = async () => {
    const data = await request(api.getStorageList);
    SetDataSource(data.data);
  };
  useEffect(() => {
    initData();
  }, []);

  return (
    <ProList<pramaryType>
      headerTitle="存储室"
      toolBarRender={() => {
        return [
          <Access key={'new'} accessible={access.normalButtonFilter('FILE_MEMORY:INSERT')}>
            <InsertComponent key={'new'} initData={initData} />
          </Access>,
          <Access key={'update'} accessible={access.normalButtonFilter('FILE_MEMORY:UPDATE')}>
            <UpdateComponent key="update" selectedRowKeys={selectedRowKeys} />
          </Access>,
          ,
          <Access key={'delete'} accessible={access.normalButtonFilter('FILE_MEMORY:DELETE')}>
            <a
              key={'delete'}
              onClick={() => {
                if (selectedRowKeys.length != 1) {
                  message.error('请选择单一项进行删除');
                  return;
                }

                Modal.warn({
                  title: '是否删除该存储室',
                  okText: '删除',
                  maskClosable: true,
                  onOk: async () => {
                    const data = await request(api.deleteStoreInfoById, {
                      params: {
                        id: selectedRowKeys[0],
                      },
                    });
                    if (data.success) {
                      message.success('删除成功');
                      initData();
                    } else {
                      message.error('删除失败');
                    }
                  },
                  onCancel: () => {},
                });
              }}
            >
              删除
            </a>
          </Access>,
        ];
      }}
      onRow={(record: any) => {
        return {
          onClick: () => {},
        };
      }}
      rowKey="id"
      split
      dataSource={dataSource}
      showActions="hover"
      bordered={true}
      rowSelection={rowSelection}
      showExtra="hover"
      metas={{
        id: {
          dataIndex: 'id',
        },
        title: {
          dataIndex: 'title',
        },
        avatar: {
          dataIndex: 'image',
          render: () => {
            return (
              <Avatar
                shape="square"
                src="https://sxit-gc.oss-cn-beijing.aliyuncs.com/tdf-bms-file/icon/%E6%96%87%E4%BB%B6%E6%9F%9C.svg"
              />
            );
          },
        },

        description: {
          dataIndex: 'deptName',
          search: false,
          render: (_, row) => {
            return (
              <Space size={0}>
                <Tag color="blue" key={row.deptName}>
                  {row.deptName}
                </Tag>
              </Space>
            );
          },
        },
      }}
    />
  );
};
